#!/usr/bin/python

import sys
sys.path.insert(0, "..")
from scraperBase import scraperBase


import xml.dom.minidom
from xml.dom.minidom import Node
from xml.dom.ext import PrettyPrint
import re


DEBUG_TEMPLATE = """<results for="transformers">
  <moviematches>
  <movie>
    <score>1.0</score>
    <popularity>12</popularity>
    <title>Transformers</title>
    <type>movie</type>
    <id>1858</id>
    <imdb>tt0418279</imdb>
    <url>http://www.themoviedb.org/movie/1858</url>
    <short_overview>Transformers is the 2007 film based 
on the popular Transformer action toy and earlier cartoon 
series that ended in 1987....</short_overview>
    <release>2007-07-04</release>
    <poster size="original">http://www...jpg</poster>
    <poster size="thumb">http://www...jpg</poster>
    <poster size="mid">http://www...jpg</poster>
    <poster size="cover">http://www...jpg</poster>
    <backdrop size="original">http://www...jpg</backdrop>
    <backdrop size="thumb">http://www...jpg</backdrop>
    <backdrop size="mid">http://www...jpg</backdrop>
  </movie>

  <movie>
    <score>0.5</score>
    <popularity>12</popularity>
    <title>Wall-e</title>
    <type>movie</type>
    <id>1858</id>
    <imdb>tt0418250</imdb>
    <url>http://www.themoviedb.org/movie/10681</url>
    <short_overview>This is some fake shit</short_overview>
    <release>1907-07-04</release>
  </movie>
  </moviematches>
</results>
"""

DEBUG_TEMPLATE_DETAILS = """
<results for="187">
  <moviematches>
  <movie>
    <score>0.707575380802155</score>
    <popularity>4</popularity>
    <title>Sin City</title>
    <type>movie</type>
    <id>187</id>
    <imdb>tt0401792</imdb>
    <url>http://www.themoviedb.org/movie/187</url>
    <short_overview>The first of three films based on 
the beautiful comic world of Frank Miller. Sin City 
depicts the comic book almost page for 
page with...</short_overview>
    <rating>6.71429</rating>
    <release>2005-04-01</release>
    <runtime>124</runtime>
    <budget>40000000</budget>
    <revenue>158733820</revenue>
    <popularity>2</popularity>
    <homepage>http://www.sincitythemovie.com/</homepage>
    <production_countries>
      <country>
        <name>United States of America</name>
        <url>http://www.../country/223</url>
      </country>
    </production_countries>
    <trailer>http://www.youtube...YKFLrTYKIXk</trailer>
    <poster size="original">http://www...jpg</poster>
    <poster size="thumb">http://www...jpg</poster>
    <poster size="mid">http://www...jpg</poster>
    <poster size="cover">http://www...jpg</poster>
    <backdrop size="original">http://www...jpg</backdrop>
    <backdrop size="mid">http://www...jpg</backdrop>
    <backdrop size="thumb">http://www...jpg</backdrop>
    <people>
      <person job="director">
        <name>Frank Miller</name>
        <url>http://www.themoviedb.org/person/2293</url>
      </person>
      <person job="author">
        <name>Frank Miller</name>
        <url>http://www.themoviedb.org/person/2293</url>
      </person>
      <person job="director">
        <name>Robert Rodriguez</name>
        <url>http://www.themoviedb.org/person/2294</url>
      </person>
   </people>
   <categories>
      <category>
        <name>Technical Format</name>
        <url>http://www.../category/10</url>
      </category>
      <category>
        <name>Black And White Film</name>
        <url>http://www.../category/301</url>
      </category>
   </categories>
  </movie>
  </moviematches>
</results>
"""

DEBUG_TEMPLATE_IMDBLOOKUP = """
<results for="tt0137523">
  <moviematches>
  <movie>
    <score>1.0</score>
    <popularity>2</popularity>
    <title>Fight Club</title>
    <type>movie</type>
    <id>550</id>
    <imdb>tt0137523</imdb>
    <url>http://www.themoviedb.org/movie/550</url>
    <short_overview>An office employee and a soap salesman 
build a global organization to help vent male 
 aggression....</short_overview>
    <release>1999-09-16</release>
    <poster size="original">http://www...jpg</poster>
    <poster size="thumb">http://www...jpg</poster>
    <poster size="mid">http://www...jpg</poster>
    <poster size="cover">http://www...jpg</poster>
    <backdrop size="original">http://www...jpg</backdrop>
    <backdrop size="thumb">http://www...jpg</backdrop>
    <backdrop size="mid">http://www...jpg</backdrop>
  </movie>
  </moviematches>
</results>

"""

THEMOVIEDB_URL = re.compile("themoviedb.org/movie/(?P<id>[0-9]*)",re.IGNORECASE)

class Scraper(scraperBase):
	name = "TheMovieDB"
	def Search(self,name,year=None):
		#http://api.themoviedb.org/2.0/Movie.search?title=transformers&api_key=5e88...
		##movieList = DEBUG_TEMPLATE.replace("SEARCH_TERM",name)
		movieList = DEBUG_TEMPLATE
		r = []
		doc = xml.dom.minidom.parseString(movieList)
		for node in doc.getElementsByTagName("movie"):
			title = node.getElementsByTagName("title")[0].firstChild.data
			url = node.getElementsByTagName("url")[0].firstChild.data
			date = node.getElementsByTagName("release")[0].firstChild.data
			r.append([title,url,date])
		#print doc
		return r
		
	def RescanCache(self,id):
		#TODO : Triggers rescan of all data in cache.
		pass
		
	def GetDetails(self,url):
		#http://api.themoviedb.org/2.0/Movie.getInfo?id=187&api_key=5e88...
		id = THEMOVIEDB_URL.findall(url)[0]
		movieDetails = self.HTTP_Get("details",id,DEBUG_TEMPLATE_DETAILS)
		
		doc = xml.dom.minidom.parseString(movieDetails)
		assert (len(doc.getElementsByTagName("movie")) == 1)
		data = doc.getElementsByTagName("movie")[0]


				#id INTEGER NOT NULL PRIMARY KEY, 
				#name TEXT NOT NULL,
				#updated DATE,
				
				#url TEXT,
				#released DATE,
				#rating REAL,
				#plot_short TEXT,
				#plot_long TEXT,
				#ended DATE,
				#status TEXT

		r = LoadElements(data,{
			'title':'title',
			'rating':'rating',
			'release':'date',
			'runtime':'runtime'})
		
		r['tags'] = []
		for x in data.getElementsByTagName("category"):
			r['tags'].append(x.getElementsByTagName("name")[0].firstChild.data)
		r['tags'].append("Movie")
		
		return r
		
	def IMDBLookup(self,imdbid):
		#query http://api.themoviedb.org/2.0/Movie.imdbLookup?imdb_id=tt0137523&api_key=5e88...
		#parse http://api.themoviedb.org/2.0/docs/details/movie.imdblookup.html
		details = self.HTTP_Get("imdbLookup",imdbid,DEBUG_TEMPLATE_IMDBLOOKUP)
				
		doc = xml.dom.minidom.parseString(details)
		data = doc.getElementsByTagName("movie")
		assert (len(data) == 1)
		data = data[0]
		return data.getElementsByTagName("url")[0].firstChild.data
		
